package com.gitee.zzh.sqllineage.util;

import com.gitee.zzh.sqllineage.vo.TableColumnInfo;
import com.gitee.zzh.sqllineage.vo.TransformVO;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ColumnInfoUtils extends SqlStringUtils {
    private static final Map<String, List<Map<String, String>>> tableColumnMap = new HashMap<>();
    public static List<Map<String, String>> getColumnsInfo(TransformVO transformVO, String tableName) {
        tableName = substringBySymbol(tableName, " ", "(", ")");
        String text = transformVO.getText();
        String tableName1 = getFinalTableName(text, tableName);
        if(!tableName1.equals(tableName)) {
            tableName = tableName1;
        }
        List<Map<String, String>> columns = tableColumnMap.get(tableName);
        if(columns != null && !columns.isEmpty()) {
            return columns;
        }
        columns = getColumnsInfoByCreateText(text, tableName);
        if(columns.isEmpty()) {
            columns = getColumnsInfoByCreateAsText(text, tableName);
        }
        if(columns.isEmpty()) {
            columns = getColumnsInfoByCreateAsText(text, tableName);
        }
        TableColumnInfo tableColumnInfo = transformVO.getTableColumnInfo();
        if(columns.isEmpty()) {
            columns = tableColumnInfo.getColumnsByTableName(tableName);
        }
        String s = "ALTER TABLE " + tableName + " RENAME TO ";
        if(columns.isEmpty() && (text.contains(s) || text.contains(" RENAME TO " + tableName + ";"))) {
            String[] textArr = transformVO.getTextArr();
            if(textArr == null) {
                textArr = text.split(";");
            }
            for (String textPart : textArr) {
                if(textPart.startsWith(s)) {
                    columns = tableColumnInfo.getColumnsByTableName(textPart.substring(s.length()));
                    break;
                }
            }
            if(columns.isEmpty()) {
                for (String textPart : textArr) {
                    if(textPart.startsWith("ALTER TABLE ") && textPart.endsWith(" RENAME TO " + tableName)) {
                        String tableName2 = textPart.substring("ALTER TABLE ".length(), textPart.length() - (" RENAME TO " + tableName).length());
                        columns = getColumnsInfoByCreateText(text, tableName);
                        if(columns.isEmpty()) {
                            columns = getColumnsInfoByCreateAsText(text, tableName2);
                        }
                        break;
                    }
                }
            }
        }
        if(!columns.isEmpty()) {
            tableColumnMap.put(tableName, columns);
        }
        return columns;
    }

}
